package com.jk.service;

import com.alibaba.fastjson.JSON;
import com.jk.dao.*;
import com.jk.entity.*;
import com.jk.pojo.UserBean;
import com.jk.utils.AliyunUtils;
import com.jk.utils.Base64Utils;
import com.jk.utils.ReturnMsgUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName UserService
 * @Descripttion TODO
 * @Author DELL
 * @Date 2022/11/2 15:29
 * @Version 0.001
 */
@Service
@SuppressWarnings("all")
public class UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RechargeableDao rechargeableDao;
    @Autowired
    private RecordInvesDao recordInvesDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private BankCardDao bankCardDao;
    @Autowired
    private WithdrawService withdrawService;



    /**
     * @Author: binzi
     * @Description:走mysql模糊登录
     * @Date: 2022/11/2 15:33
     * @Return: java.util.Map
     **/
    public Map login(UserBean user, HttpSession session) {
        //先去数据库根据账号查询或者手机号
        UserBean user2 = userDao.findUserByName(user.getUser_name(),user.getUser_phone());
        RedisEntity redisEntity = new RedisEntity();
        //判断账号是否存在
        if (user2 != null){//存在
            if (user.getUser_pwd().equals(Base64Utils.decodeData(user2.getUser_pwd()))){//密码正确
                session.setAttribute("user",user2);
                UserBean user1 = (UserBean) session.getAttribute("user");
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                redisEntity.setUserName(user2.getUser_name());
                redisEntity.setCurrentTime(df.format(new Date()));
                redisEntity.setOperation("登录成功！！！");
                String uuid = UUID.randomUUID().toString().replace("-", "");
                redisTemplate.opsForHash().put(user2.getUser_id(),uuid,redisEntity);
                redisTemplate.opsForValue().set("denglu",user2,36000, TimeUnit.SECONDS);
                return ReturnMsgUtils.returnMsg(200,"登录成功！！！",null);
            }else {//密码错误
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                redisEntity.setUserName(user2.getUser_name());
                redisEntity.setCurrentTime(df.format(new Date()));
                redisEntity.setOperation("密码错误！！！");
                String uuid = UUID.randomUUID().toString().replace("-", "");
                redisTemplate.opsForHash().put(user2.getUser_id(),uuid,redisEntity);
                return ReturnMsgUtils.returnMsg(500,"账号或者密码错误！！！",null);
            }
        }else {//不存在
            return ReturnMsgUtils.returnMsg(500,"账号或者密码错误！！！",null);
        }
    }

    public List<RedisEntity> getRedisList(HttpSession session) {
        UserBean user = (UserBean) session.getAttribute("user");
        Map<Object,Object> entries = redisTemplate.opsForHash().entries(user.getUser_id());
        List<RedisEntity> redisEntities = new ArrayList<>();
        entries.forEach((key,value)->{
            redisEntities.add((RedisEntity) value);
        });
        return redisEntities;
    }

    /**
    * @Author: binzi
    * @Description:短信接口
    * @Date: 2022/11/4 16:29
    * @Return: java.lang.Object
    **/
    public void SmsVerificationOne(String phone,HttpSession session) {
        String code = "1111";
        try {
            UserBean user = (UserBean) redisTemplate.opsForValue().get("denglu");
            if (phone !=null && phone !=""){
//                AliyunUtils.sendSms(phone,session);
//                String code = (String) session.getAttribute("code");
                redisTemplate.opsForValue().set(phone,code,999999999, TimeUnit.MINUTES);
            }else {
//                AliyunUtils.sendSms(user.getUser_phone(),session);
//                String code = (String) session.getAttribute("code");

                redisTemplate.opsForValue().set(user.getUser_phone(),code,999999999, TimeUnit.MINUTES);
            }
        } catch (Exception e) {
            e.getMessage();
        }
    }

    public Map registeredUser(UserBean userBean,String code) {
        UserBean userBean1 = userDao.getPhone(userBean.getUser_phone());
        if (userBean1 == null){
            String code1 = (String) redisTemplate.opsForValue().get(userBean.getUser_phone());
            if (code.equals(code1)){
                String s = Base64Utils.encodeData(userBean.getUser_pwd());
                userBean.setUser_pwd(s);
                userDao.insert(userBean);
                return ReturnMsgUtils.returnMsg(200,"注册成功",null);
            }
            else {
                return ReturnMsgUtils.returnMsg(400,"验证码错误",null);
            }
        }
        else {
            return ReturnMsgUtils.returnMsg(500,"已有用户请直接登录",null);
        }

    }

    public Map updatePwd(UserBean userBean, String code) {
        if (userBean.getUser_phone() !=null&&userBean.getUser_phone() !=""&&userBean.getUser_phone().length() ==11){
            UserBean userBean1 = userDao.getPhone(userBean.getUser_phone());
            if (userBean1 != null){
                String code1 = (String) redisTemplate.opsForValue().get(userBean.getUser_phone());
                if (code.equals(code1)){
                    userBean1.setUser_pwd(userBean.getUser_pwd());
                    return ReturnMsgUtils.returnMsg(200,"成功",null);
                }
                else {
                    return ReturnMsgUtils.returnMsg(400,"验证码错误",null);
                }
            }else {
                return ReturnMsgUtils.returnMsg(500,"暂无此用户,请注册",null);
            }
        }
        else {
            UserBean denglu = (UserBean) redisTemplate.opsForValue().get("denglu");
            String code1 = (String) redisTemplate.opsForValue().get(denglu.getUser_phone());
            if (code.equals(code1)){
                return ReturnMsgUtils.returnMsg(200,"成功",null);
            }
            else {
                return ReturnMsgUtils.returnMsg(400,"验证码错误",null);
            }
        }

    }

    public Boolean getSessionUser(HttpSession session) {
        UserBean userBean1 = (UserBean) redisTemplate.opsForValue().get("denglu");
        UserBean userBean = (UserBean) session.getAttribute("user");
        if (userBean1 == null){
            return false;
        }else {
            return true;
        }
    }

    public Map updateUserPassward(UserBean userBean) {
                String pwd = Base64Utils.encodeData(userBean.getUser_pwd());
                userBean.setUser_pwd(pwd);
        try {
            if (userBean.getUser_phone() != null && userBean.getUser_phone() != "" && userBean.getUser_phone().length() == 11){
                userDao.updateUserPassward(userBean);
                return  ReturnMsgUtils.returnMsg(200,"修改成功",null);
            }else {
                UserBean userBean1 = (UserBean) redisTemplate.opsForValue().get("denglu");
                userBean.setUser_phone(userBean1.getUser_phone());
                userDao.updateUserPassward(userBean);
                return  ReturnMsgUtils.returnMsg(200,"修改成功",null);
            }
        }catch (Exception e){
            e.getMessage();
            return  ReturnMsgUtils.returnMsg(500,"修改失败",null);
        }

    }

    public UserBean selectUserEntity() {
        UserBean userBean= (UserBean) redisTemplate.opsForValue().get("denglu");
        return userBean;
    }

    /**
    * @Author: binzi
    * @Description:支付宝充值修改用户金额
    * @Date: 2022/11/7 17:44
    * @Return: void
    **/
    public void updateMoney(String total_amount) {
        UserBean user = (UserBean) redisTemplate.opsForValue().get("denglu");
        BigDecimal bigDecimal = new BigDecimal(total_amount);
        user.setMoney(bigDecimal);
        RechargeableEntity rechargeableEntity = new RechargeableEntity();
        rechargeableEntity.setFinancialDetailsIncome(bigDecimal);
        rechargeableEntity.setFinancialDetailsBalance(user.getUser_balance().subtract(bigDecimal));
        Date myDate = new Date();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        String strDate1 = sdf1.format(myDate);
        rechargeableEntity.setFinancialDetailsDate(strDate1);
        rechargeableEntity.setFinancialDetailsTypeId(1);
        rechargeableEntity.setFinancialDetailsName("支付宝");
        rechargeableEntity.setFinancialUserPhone(user.getUser_phone());
        rechargeableDao.insert(rechargeableEntity);
        userDao.updateMoney(user.getUser_phone(),user.getMoney());
        withdrawService.getByIdUserMoney();
    }

    /**
     * @Author: binzi
     * @Description:银行卡充值
     * @Date: 2022/11/8 9:38
     * @Return: java.util.Map
     **/
    public Map bankCardTopUp(BusinessEntity businessEntity) {
        UserBean user = (UserBean) redisTemplate.opsForValue().get("denglu");
        String code1 = (String) redisTemplate.opsForValue().get(user.getUser_phone());
        if (businessEntity.getT_code().equals(code1)){
            UserBean user1 = userDao.getPhone(user.getUser_phone());
            if (businessEntity.getT_pwd().equals(user1.getUser_with())){
                //根据银行卡号回显
                BankCardEntity bankCardEntity = userDao.findBankCardByCode(businessEntity.getT_bank_code());
                int i = bankCardEntity.getBank_card_balance().compareTo(businessEntity.getT_money());
                if (i  == 1){
                    //修改用户余额
                    userDao.updateMoney(user.getUser_phone(),businessEntity.getT_money());
                    //修改银行卡余额
                    userDao.updateBankCardMoney(businessEntity.getT_bank_code(),businessEntity.getT_money());

                    RechargeableEntity rechargeableEntity = new RechargeableEntity();
                    rechargeableEntity.setFinancialDetailsIncome(businessEntity.getT_money());
                    rechargeableEntity.setFinancialDetailsBalance(user.getUser_balance().subtract(businessEntity.getT_money()));
                    Date myDate = new Date();
                    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
                    String strDate1 = sdf1.format(myDate);
                    rechargeableEntity.setFinancialDetailsDate(strDate1);
                    rechargeableEntity.setFinancialDetailsTypeId(1);
                    rechargeableEntity.setFinancialDetailsName(bankCardEntity.getBank_card_name());
                    rechargeableEntity.setFinancialUserPhone(user.getUser_phone());
                    rechargeableDao.insert(rechargeableEntity);
                    withdrawService.getByIdUserMoney();
                    return ReturnMsgUtils.returnMsg(200,"支付成功",null);
                }else {
                    return ReturnMsgUtils.returnMsg(500,"银行卡不足！！！",null);
                }
            }else {
                return ReturnMsgUtils.returnMsg(500,"支付密码错误！！！",null);
            }
        }
        else {
            return ReturnMsgUtils.returnMsg(400,"验证码无效",null);
        }
    }

    /**
     * @Author: binzi
     * @Description:根据手机号查询对应的银行卡号
     * @Date: 2022/11/8 11:24
     * @Return: java.util.Map
     **/
    public Map findBankCardByPhone() {
        UserBean user = (UserBean) redisTemplate.opsForValue().get("denglu");
        ArrayList<BankCardEntity> lists = new ArrayList<>();
        List<BankCardEntity> list = userDao.findBankCardByPhone(user.getUser_phone());
        list.forEach(BankCardEntity->{
            BankCardEntity.setBank_card_code(Base64Utils.decodeData(BankCardEntity.getBank_card_code()));
            lists.add(BankCardEntity);
        });
        return ReturnMsgUtils.returnMsg(200,"根据手机号查询对应的银行卡号",lists);
    }

    /*
    *
     * @Author 位佳生
     * @Description //TODO 退出登录
     * @Date 2022/11/10 9:39
     * @param session:
     * @Date 2022/11/10 10:23
     * @param session:
     * @return: java.lang.Boolean
     **/
    public Boolean removeUser(HttpSession session) {
        try {
            session.removeAttribute("user");
            redisTemplate.delete("denglu");
            return true;
        }catch (Exception e){
            e.getMessage();
            return false;
        }
    }

    /**
     * @Author: binzi
     * @Description:获取登录用户人信息
     * @Date: 2022/11/10 9:41
     * @Return: java.util.Map
     **/
    public Map findUserByPhone() {
        UserBean user = (UserBean) redisTemplate.opsForValue().get("denglu");
        return ReturnMsgUtils.returnMsg(200,"获取登录用户人信息",user);
    }

    /**
     * @Author: binzi
     * @Description:根据登录的用户修改支付密码
     * @Date: 2022/11/10 10:31
     * @Return: java.util.Map
     **/
    public Map updateUserWith(String user_with) {
        UserBean user = (UserBean) redisTemplate.opsForValue().get("denglu");
        String with = Base64Utils.encodeData(user_with);
        userDao.updateUserWith(user.getUser_phone(),with);
        return ReturnMsgUtils.returnMsg(200,"根据登录的用户修改支付密码",true);
    }

    /**
    * @Author: binzi
    * @Description:实名认证
    * @Date: 2022/11/10 11:12
    * @Return: void
    **/
    public void updateUserByPhoneAndIdCard(String name, String idcard) {
        UserBean user = (UserBean) redisTemplate.opsForValue().get("denglu");
        String idcards = Base64Utils.encodeData(idcard);
        userDao.updateUserByPhoneAndIdCard(name,idcards,user.getUser_phone());
    }

    /**
     * @Author: binzi
     * @Description:新增银行卡号
     * @Date: 2022/11/10 11:39
     * @Return: java.util.Map
     **/
    public Map insertBankCard(BankCardEntity bankCardEntity) throws IOException {
        Map finndcard = finndcard(bankCardEntity.getBank_card_code());
        if (finndcard.get("validated").equals(true)){
            try {
                UserBean denglu = (UserBean) redisTemplate.opsForValue().get("denglu");
                String code1 = (String) redisTemplate.opsForValue().get(denglu.getUser_phone());
                if (bankCardEntity.getCode().equals(code1)){
                    BankCardEntity bankCardEntity1 = new BankCardEntity();
                    bankCardEntity1.setBank_card_code(Base64Utils.encodeData(bankCardEntity.getBank_card_code()));
                    bankCardEntity1.setBank_card_transaction_pwd(bankCardEntity.getBank_card_transaction_pwd());
                    bankCardEntity1.setBank_card_img("https://www.pmdaniu.com/storages/95426/97f230b908d89c7dbabd8ff0abd1f51a-1818/images/%E5%85%85%E5%80%BC/p15.jpg");
                    bankCardEntity1.setBank_card_name("工商银行");
                    BigDecimal bigDecimal = new BigDecimal(10000.00);
                    bankCardEntity1.setBank_card_balance(bigDecimal);
                    bankCardEntity1.setBank_card_phone(denglu.getUser_phone());
                    String bank = (String) finndcard.get("bank");
                    bankCardEntity1.setBank_card_type(bank);
                    bankCardDao.insert(bankCardEntity1);
                    return ReturnMsgUtils.returnMsg(200,"成功",null);
                }
                else {
                    return ReturnMsgUtils.returnMsg(400,"验证码错误",null);
                }

            }catch (Exception e){
                e.getMessage();
                return  ReturnMsgUtils.returnMsg(500,"新增银行卡号",false);
            }
        }else {
            return  ReturnMsgUtils.returnMsg(500,"银行卡无效！！！",false);
        }

    }
    /*
     *
     * @Author 位佳生
     * @Description //TODO 计算总资产
     * @Date 2022/11/10 11:20
     * @param null:
     * @return: null
     **/
    public Map sumPrice() {
            try {
                UserBean user = (UserBean) redisTemplate.opsForValue().get("denglu");
                BigDecimal  sumPrice = recordInvesDao.sumPrice(user.getUser_id());
                BigDecimal  userSumPrice = user.getUser_balance().add(sumPrice);
                return ReturnMsgUtils.returnMsg(200,"查询成功",userSumPrice);
            }catch (Exception e){
                e.getMessage();
                UserBean user = (UserBean) redisTemplate.opsForValue().get("denglu");
                return ReturnMsgUtils.returnMsg(200,"查询成功",user.getUser_balance());
            }
    }
    /*
     *
     * @Author 位佳生
     * @Description //TODO 计算投资中本金
     * @Date 2022/11/10 11:20
     * @param null:
     * @return: null
     **/
    public Map sumMoney() {
        try {
            UserBean user = (UserBean) redisTemplate.opsForValue().get("denglu");
            BigDecimal  sumPrice = recordInvesDao.sumPrice(user.getUser_id());
            return ReturnMsgUtils.returnMsg(200,"查询成功",sumPrice);
        }catch (Exception e){
            e.getMessage();
            return ReturnMsgUtils.returnMsg(200,"暂未投资",0);
        }
    }
    /*
     *
     * @Author 位佳生
     * @Description //TODO 计算历史到账收益
     * @Date 2022/11/10 11:20
     * @param null:
     * @return: null
     **/
    public Map sumCountMoney() {
        try {
            UserBean user = (UserBean) redisTemplate.opsForValue().get("denglu");
            BigDecimal  sumCountMoney = recordInvesDao.sumCountMoney(user.getUser_id());
            return ReturnMsgUtils.returnMsg(200,"暂未投资",sumCountMoney);
        }catch (Exception e){
            e.getMessage();
            return ReturnMsgUtils.returnMsg(200,"暂未投资",0);
        }
    }
    /*
    *
     * @Author 位佳生
     * @Description //TODO 调取银行卡接口
     * @Date 2022/11/15 21:10
     * @param cardNo:
     * @return: java.util.Map
     **/
    public Map finndcard(String cardNo) throws IOException {
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 参数
        StringBuffer params = new StringBuffer();
        params.append("cardNo="+cardNo);
        params.append("&");
        params.append("cardBinCheck=true");
        // 创建Get请求
        HttpGet httpGet = new HttpGet("https://ccdcapi.alipay.com/validateAndCacheCardInfo.json" + "?" + params);
        // 响应模型
        CloseableHttpResponse response = null;
        // 配置信息
        RequestConfig requestConfig = RequestConfig.custom()
                // 设置连接超时时间(单位毫秒)
                .setConnectTimeout(5000)
                // 设置请求超时时间(单位毫秒)
                .setConnectionRequestTimeout(5000)
                // socket读写超时时间(单位毫秒)
                .setSocketTimeout(5000)
                // 设置是否允许重定向(默认为true)
                .setRedirectsEnabled(true).build();

        // 将上面的配置信息 运用到这个Get请求里
        httpGet.setConfig(requestConfig);

        // 由客户端执行(发送)Get请求
        response = httpClient.execute(httpGet);

        // 从响应模型中获取响应实体
        HttpEntity responseEntity = response.getEntity();
        String s = EntityUtils.toString(responseEntity);
        Map map = JSON.parseObject(s, Map.class);
        return map;
    }
}
